package edu.fiu.cis.personalize.server;

import java.util.ArrayList;
import java.util.Iterator;

import uk.org.catnip.eddie.FeedData;
import uk.org.catnip.eddie.parser.Parser;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import edu.fiu.cis.personalize.client.PersonalizedSearchService;
import edu.fiu.cis.personalize.shared.GoogleDocument;
import edu.fiu.cis.personalize.shared.IBlock;
import edu.fiu.cis.personalize.shared.ManagedBlock;
import edu.fiu.cis.personalize.shared.User;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class PersonalizedSearchServiceImpl extends RemoteServiceServlet
		implements PersonalizedSearchService {

	@Override
	public ArrayList<GoogleDocument> search(final String query) {
		return ManagedBlock
				.exceptionHandled(new IBlock<Void, ArrayList<GoogleDocument>>() {

					@Override
					public ArrayList<GoogleDocument> execute() throws Exception {
						Parser parser = new Parser();

						FeedData feed = parser
								.parse("https://www.googleapis.com/customsearch/v1?key=AIzaSyCpq0o9gXSvcVruH343mMzTsP0c5UP1kCg&cx=013036536707430787589:_pqjad5hr1a&alt=atom&q="
										+ query);
						ArrayList<GoogleDocument> list = new ArrayList<GoogleDocument>();
						Iterator<uk.org.catnip.eddie.Entry> iter = feed
								.entries();
						while (iter.hasNext()) {
							uk.org.catnip.eddie.Entry e = iter.next();
							GoogleDocument document = new GoogleDocument(e
									.getSource().links().next().toString(), e
									.getTitle().getValue(), e.getSummary()
									.getValue());
							list.add(document);
						}

						return list;
					}

					@Override
					public void handleException(Exception e) {
						throw new RuntimeException(e);
					}
				});
	}

	@Override
	public void clickGoogleDocument(String url, User user) {
		System.out.println("URL := " + url + " user: " + user.getName());

	}

	@Override
	public void cronUpdate() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		PersonalizedSearchServiceImpl impl = new PersonalizedSearchServiceImpl();
		ArrayList<GoogleDocument> d = impl.search("beautiful flowers");
		for (GoogleDocument g : d){
			System.out.println(g.getTitle());
		}
		
	}

}
